package pers.lipeng.design_pattern.building_mode._1_singleton_mode._5_double_detection_lock;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author APengG
 * 双重检测锁式单例模式
 * 优点：延时加载
 * (因为JVM本质重排序的原因，可能会初始化多次，不推荐使用)
 */
@SuppressWarnings("unused")
class Demo {
    /**
     * 双重检测锁共享变量最好加上volatile关键字保证线程可见性
     */
    private static volatile Demo demo;
    private static boolean flag = false;

    public Demo(){
        if (!flag){
            flag = true;
        }else{
            throw new RuntimeException("单例模式被侵犯！");
        }
    }

    public static Demo getInstance(){
        if (demo == null){
            synchronized (Demo.class){
                if (demo == null){
                    demo = new Demo();
                }
            }
        }
        return demo;
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Demo demo1 = Demo.getInstance();
        Demo demo2 = Demo.getInstance();
        System.out.println(demo1 == demo2);
        Constructor<?> constructor = Demo.class.getConstructor();
        Object obj = constructor.newInstance();
        System.out.println(obj);

    }
}
